#!/bin/sh
# 1.0.0
# ./dump_interactive.sh then choose one process.
#
echo "********** Welcome to Sea Tools Power by SPY. *************"
echo "****** You should use root or admin role of system. ******"

PROCESS_LIST=$(jps -vl | grep -v 'sun.tools.jps.Jps' | grep -v grep | awk -F " " '{print $1,$2,$3}' |sed 's/ /:/g')
if [ -z "$PROCESS_LIST" ]; then
    echo "No Java Processes"
    return;
fi
# 56832:/opt/operator-all/operator-web.jar:-Xmx1g

echo "Please choose One Java Application:"
select var in $PROCESS_LIST; do
  break;
done
echo "You have selected $var"

PID=${var%%:*}

dump_all() {
    datetime=`date '+%m%d_%H%M%S'`

    echo $datetime
    JSTACK_FILE=${datetime}jstack.log
    JMAP_FILE=${datetime}jmap.log
    HEAP_FILE=${datetime}heap.hprof

    JSTACK_ZIP_FILE=${JSTACK_FILE}.tgz
    JMAP_ZIP_FILE=${JMAP_FILE}.tgz
    HEAP_ZIP_FILE=${HEAP_FILE}.tgz

    dump_jstack
    dump_jmap
    dump_heap
    tar_jstack
    tar_jmap
    tar_heap
}



dump_jstack() {
    echo 'dump jstack'
    jstack -l $PID > $JSTACK_FILE
    echo 'dump jstack ok'
}

dump_jmap() {
    echo 'dump jmap'
    jmap -histo $PID  > $JMAP_FILE
    echo 'dump jmap ok'
}

dump_heap() {
    echo 'dump jmap memory'
    jmap -dump:format=b,file=$HEAP_FILE $PID
    echo 'dump jmap memory ok'
}

tar_jstack() {
    echo 'tar jstack'
    tar zcvf $JSTACK_ZIP_FILE $JSTACK_FILE
    echo 'tar jstack ok'
}

tar_jmap() {
    echo 'tar jmap'
    tar zcvf $JMAP_ZIP_FILE $JMAP_FILE
    echo 'tar jmap ok'
}

tar_heap() {
    echo 'tar jmap memory'
    tar zcvf $HEAP_ZIP_FILE $HEAP_FILE
    echo 'tar jmap memory ok'
}

# main
if [[ $PID =~ ^[0-9]+$ ]]
then
    dump_all
else
    echo "PID is invalid. Quit"
fi